//
//  LoginViewController.m
//  CenturyCity
//
//  Created by beisheng03 on 2017/11/27.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "LoginViewController.h"
#import "UserLoginCell.h"
#import "UserLoginBottomCell.h"
#import "UserLoginPNCell.h"
#import "UserLoginPWDCell.h"
#import "BaseTabBarController.h"
#import "RegisterController.h"
#import "ResetPasswordVC.h"

#import "UserInfo.h"

#import <JPUSHService.h>
@interface LoginViewController ()<UITableViewDelegate,UITableViewDataSource,UserLoginBottomCellDelegate>

/** <#note#> */
@property (nonatomic, weak) UIButton *dissBtn;
@end

@implementation LoginViewController


/**
 * 会员重置密码
 * uid             用户uid
 * newPassword     用户重置的新密码
 http://feidu.baonongkang.cn/index.php/api/Member/resetUserPassword
 
 
 
 * 会员修改密码
 * uid              用户uid
 * newPassword     用户修改的新密码
 * oldPassword      旧密码
 http://feidu.baonongkang.cn/index.php/api/Member/updateUserPassword

 */



- (UIButton *)dissBtn{
    
    if (!_dissBtn) {
        
        UIButton *temp = [UIButton buttonWithType:UIButtonTypeCustom];
        
        CGFloat tempY = IPhoneX ? 44 : 20;
        
        temp.frame = CGRectMake(0, tempY, 72, 46);
        
        temp.titleLabel.font = MYFONT(19);
        
        [temp setTitle:@"取消" forState:UIControlStateNormal];
        
        [temp setTitle:@"取消" forState:UIControlStateHighlighted];
        
        [temp setTitleColor:themeColor forState:UIControlStateNormal];
        [temp setTitleColor:themeColor forState:UIControlStateHighlighted];

        [temp addTarget:self action:@selector(dissCurrentVC) forControlEvents:UIControlEventTouchUpInside];
        _dissBtn = temp;
        
        [self.view addSubview:_dissBtn];
    }
    
    
    return _dissBtn;
}

- (void)dissCurrentVC{
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    self.tableView.delegate = self;
    
    self.tableView.dataSource = self;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    
//    self.tableView.safeAreaInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    
    if (@available(iOS 11.0, *)) {
        
        self.tableView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);
//        self.navigationController.navigationBar.prefersLargeTitles = YES;
//        self.navigationItem.largeTitleDisplayMode =  UINavigationItemLargeTitleDisplayModeAlways;
    }
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([UserLoginCell class]) bundle:nil] forCellReuseIdentifier:[UserLoginCell identifierStr]];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([UserLoginBottomCell class]) bundle:nil] forCellReuseIdentifier:[UserLoginBottomCell identifierStr]];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([UserLoginPNCell class]) bundle:nil] forCellReuseIdentifier:[UserLoginPNCell identifierStr]];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([UserLoginPWDCell class]) bundle:nil] forCellReuseIdentifier:[UserLoginPWDCell identifierStr]];

    
    self.dissBtn.backgroundColor = [UIColor clearColor];

    
    // Do any additional setup after loading the view.
}



- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    

    return 4;
  
    
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        UserLoginCell *cell = [tableView dequeueReusableCellWithIdentifier:[UserLoginCell identifierStr]];
        return cell;
    } else if (indexPath.row == 1) {
        UserLoginPNCell *cell = [tableView dequeueReusableCellWithIdentifier:[UserLoginPNCell identifierStr]];
        cell.controller = self;
        return cell;
    }else if (indexPath.row == 2) {
        UserLoginPWDCell *cell = [tableView dequeueReusableCellWithIdentifier:[UserLoginPWDCell identifierStr]];
        cell.controller = self;
        return cell;
    }else{
        
        UserLoginBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:[UserLoginBottomCell identifierStr]];
        
        cell.delegate = self;

      return cell;
    }
    
    
  
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.row == 0) {
        
        return (KScreenH - 120) * 0.5 - 30;
   
        
    } else if (indexPath.row == 1) {
        
        return 60;
        
    }else if (indexPath.row == 2) {
        
        return 60;
        
    }else{
        

        return (KScreenH - 120) * 0.5 + 30;

        
        
    }
    
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.00001;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return 0.00001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    
    return  [[UIView alloc]init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return  [[UIView alloc]init];
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    [self.view endEditing:YES];
}



- (void)registerBtnDidTap{
    
    RegisterController *resister = [[RegisterController alloc]init];

    if ([[NetworkTools shareNetworkTools]isEmailAdress:self.userTextField.text]) {
        resister.registerModel.email = self.userTextField.text;
    }

    
    [self.navigationController pushViewController:resister animated:YES];
}


- (void)forgotPasswordBtnDidTap{
    
    
    ResetPasswordVC *reset = [[ResetPasswordVC alloc]init];
    
    if ([[NetworkTools shareNetworkTools]isEmailAdress:self.userTextField.text]) {
        reset.registerModel.email = self.userTextField.text;
    }
    
    
    [self.navigationController pushViewController:reset animated:YES];
    
    
}



- (void)loginBtnDidTap{
    
    [self.view endEditing:YES];
    
    
    if (self.userTextField.text == nil) {

        [SVProgressHUD showInfoWithStatus:@"请填写用户名"];

        return;
    }
    


    BOOL isEmail = [[NetworkTools shareNetworkTools] isEmailAdress:self.userTextField.text];

//    BOOL istelephoneNumber = [[NetworkTools shareNetworkTools] isPhoneNumber:self.userTextField.text];

//    if ((!istelephoneNumber) && (!isEmail)) {
//
//        [SVProgressHUD showInfoWithStatus:@"用户名号格式不正确!"];
//
//        return;
//
//    }
    
    if (!isEmail) {
        
        [SVProgressHUD showInfoWithStatus:@"用户名号格式不正确!"];
        
        return;
        
    }
    
    
    
    if (self.pwdTextField.text == nil) {
        
        [SVProgressHUD showInfoWithStatus:@"请填写登录密码!"];
        
        return;
    }
    
    if (self.pwdTextField.text.length <  6) {
        
        [SVProgressHUD showInfoWithStatus:@"密码格式不正确!"];
        
        return;
    }
    
    

    [SVProgressHUD showWithStatus:@"正在登录..."];

    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"username"] = self.userTextField.text;
    parameters[@"password"] = self.pwdTextField.text;
    
    __weak typeof (self) weakSelf = self;
    [[NetworkTools shareNetworkTools] sendRequestWithHttpMethod:POST_METHOD URLPath:@"Member/login" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (error) {
            
            [SVProgressHUD showErrorWithStatus:error.domain];
            
        } else {
            
            [SVProgressHUD dismiss];
            
            MYJSONSTR
            
            UserInfo *userModel =  [UserInfo mj_objectWithKeyValues:responseObject[@"data"]];

            [UserViewModel shareUserViewModel].user = userModel;

            [userModel saveUserInfo];
            
            [weakSelf setupJpush];
            
            [weakSelf saveUserImage];
            
            
              [[NSNotificationCenter defaultCenter]postNotificationName:@"userDidLoginOrInfoChange" object:nil];

            [weakSelf didSussessLoagin];
        }
        
    }];
    
    
    
}





- (void)setupJpush{
    
    [JPUSHService setTags:[NSSet setWithObject:@"feifubao"] completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
        
        NSLog(@"%ld++++++",(long)iResCode);
        
    } seq:myViewModel.user.user_tel.integerValue];
    
    
    [JPUSHService setAlias:myViewModel.user.uid completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
        NSLog(@"%ld+++++++",(long)iResCode);
        
        
    } seq:myViewModel.user.user_tel.integerValue + 1];
    
}



- (void)saveUserImage{
    
    
    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:myViewModel.user.user_headimg] options:kNilOptions progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        
        
        NSLog(@"22222222222");
        
    }];
    
    
}


- (void)didSussessLoagin{
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
//    CATransition *tranition = [CATransition animation];//转场动画
//
//    tranition.type = @"reveal";//动画类型
//
//    tranition.duration = 0.5;//动画时长
//
//
//    [[UIApplication sharedApplication].keyWindow.layer addAnimation:tranition forKey:nil];
//
//
//    [UIApplication sharedApplication].keyWindow.rootViewController = [[BaseTabBarController alloc]init];
}




    


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)dealloc{
    
    NSLog(@"%@",self.class);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
